<template>
	<view>
		<view class="image-box">
			<view class="img-upload">
				<view class="top-tips">
					*图片限10M以内 <!--<text class="red">(温馨提示：不支持工商银行)</text>-->
				</view>
				<view class="box-image" @click="chooseImg('04')">
					<image class="bg-image" :src="
			    bankImage
			      ? bankImage
			      : require('@/common/images/identification/img-card-number-photo.png')
			  " mode="aspectFill"></image>
					<view class="add">+</view>
				</view>
				<view class="tips"> 请上传收款卡卡号面照片 </view>
			</view>
			<!-- <view class="img-upload">
				<view class="box-image" @click="chooseImg('14')">
					<image class="bg-image" :src="
			    bankBackImage
			      ? bankBackImage
			      : require('@/common/images/identification/img-card-number-photo.png')
			  " mode="aspectFill"></image>
					<view class="add">+</view>
				</view>
				<view class="tips"> 请上传收款卡反面照片 </view>
			</view> -->
		</view>
		<view class="form">
			<view class="item">
				<text class="text">结算卡号</text>
				<input class="input" placeholder="请输入结算卡号" v-model="form.settleCardNo" type="text" />
			</view>
			<view class="item">
				<text class="text">开户行名称</text>
				<input class="input" @click="bankNameClick" placeholder="请输入开户行名称" v-model="form.bankName"
					type="text" />
			</view>

			<view class="item">
				<text class="text">开户省市</text>
				<view class="" @click="areaShow=true">
					<picker mode="multiSelector" :value="areaIndex" :range="pickerRange" @columnchange="columnchange"
						range-key="name" @change="onChange">
						{{ form.areaText?form.areaText:'请选择' }}
						<i class="iconfont icon-Downarrow-R"></i>
					</picker>
				</view>
				<!-- <u-picker mode="region" v-model="areaShow" @confirm="areaConfirm"></u-picker> -->

			</view>
			<!-- <view class="item">
				<text class="text">开户省市</text>
				<uni-data-picker split=" " class="area-picker" :localdata="areaData"
					:popup-title="form.areaText ? form.areaText : '请选择城市'" @change="onchange">
					{{ form.allArea }}
				</uni-data-picker>
			</view> -->

			<view class="item">
				<text class="text">开户支行</text>
				<!-- <view class="bank-show">
					<input class="input" placeholder="请输入预留手机号" v-model="form.phone" type="text" />
					<i class="iconfont icon-Downarrow-R"></i>
				</view> -->
				<picker class="input" mode="selector" range-key="name" :range="bankList" @change="pickerConfirmHandle">
					<view class="uni-input">
						{{form.stlBankNm ? form.stlBankNm :'请选支行'}}
					</view>
					<!-- 	<view class="uni-input">
						{{
					  bankChooseIndex != -1
					    ? bankList[bankChooseIndex].name
					    : "请选择支行"
					}}
					</view> -->
				</picker>
				<i class="iconfont icon-Downarrow-R"></i>
			</view>
			<view class="item">
				<text class="text">预留手机号</text>
				<input class="input" placeholder="请输入银行卡预留手机号" v-model="form.phone" type="text" />
			</view>
			<view class="item" >
				<text class="text">验证码：</text>
				<input class="input" placeholder="请输入验证码" v-model="form.scanSmsCode" type="text" />
				<u-button class="sendCode" size="mini" type="warning" shape="circle" :disabled="disabled"
					@click="sms">{{ second == 0 ? '发送验证码' : second + '秒' }}</u-button>
			</view>
			<view class="card-btn flex-space-between">
				<view class="button next" @click="backSubmit" v-if="type == 4">上一步</view>
				<view class="button next" @click="cardSubmit">提交</view>
			</view>
		</view>
		<w-compress ref="wCompress2" />
	</view>
</template>

<script>
	// import areaData from "_c/utils/area";
	import areaData from "_c/utils/area2";
	import {
		smsSend,
		getBankCode,
		subBankCode,
		getProvinceCityList,
	} from "_a/system";
	import {
		informationQuery,
		queryCustomer
	} from "_a/user";
	import uploadImgMixin from "@/mixins/uploadImg";
	import signSmsMixin from "@/mixins/signSms";
	import {
		getProvinceApi,
		getAreaApi,
		getCityApi
	} from '_a/home';
	export default {
		mixins: [uploadImgMixin,signSmsMixin],
		props: {
			type: {
				default: 4, //5:修改 4:添加
			},
			cardData: {},
			res: null
		},
		data() {
			return {
				form: {
					settleCardNo: "",
					phone: "",
					bankName: "",
					areaText: "请选择地区",
					bankType: '',
					bankCode: '',
				},
				// type: 4, //5:修改 4:添加
				bankImage: "",
				bankBackImage: "",
				second: 0,
				disabled: false,
				areaData: areaData,
				// areaData: {},
				bankList: [], //银行卡列表
				bankChooseIndex: -1,
				bItem: null, // 失败数据
				areaShow: false,
				provinceList: [],
				cityApiList: [],
				areaApiList: [],
				pickerRange: [
					[],
					[],
					[]
				],
				areaIndex: [0, 0, 0],
				channelCode: ''
			};
		},
		created() {

		},
		computed: {
			// 是否机具扫码进入
			terminalInto() {
				return this.$store.getters.terminalInto || false
			}
		},
		onLoad(option) {
			// this.type = option.type;
			switch (Number(this.type)) {
				case 1:
					let bItem = this.$storage.getStore("bandCardAuditItem") || null;
					this.bItem = bItem;
					// console.log(bItem)
					break;
				default:
					this.form.allArea = "请选择地区";
					break;
			}
		},
		methods: {
			async loadingInfo() {
				
				//加载数据
				await this.$store.dispatch('getUserDetail').then(res => {
					this.res = res;
				})
				const scanSerialno = this.$storage.getStore('serialno');
				let result = await queryCustomer({scanSerialno});
				this.res = result.data;
				this.channelCode = result.data.channelCode;
				this.initAddressData();
				this.getData();
			},
			// 获取地址接口信息
			async initAddressData() {
				const addressData = this.areaData;
				this.pickerRange[0] = await this.getProvinceApiData(this.channelCode);
				this.pickerRange[1] = await this.getCityApiData(this.pickerRange[0][0].code, this.channelCode);
				this.pickerRange[2] = await this.getAreaApiData(this.pickerRange[1][0].code, this.channelCode);
			},
			// 地址每列选择
			async columnchange(event) {
				let {
					column,
					value
				} = {
					...event.detail
				};
				if (column == 0) {
					this.pickerRange[1] = await this.getCityApiData(this.pickerRange[0][value].code, this.channelCode);
					this.pickerRange[2] = await this.getAreaApiData(this.pickerRange[1][0].code, this.channelCode);
					this.$set(this.areaIndex, column, value);
				}
				if (column == 1) {
					this.pickerRange[2] = await this.getAreaApiData(this.pickerRange[1][value].code, this.channelCode);
					this.$nextTick(() => {
						this.areaIndex[2] = 0;
					});
				}
				await this.$forceUpdate();
			},
			// 地址选择确定
			onChange(e) {
				const index = e.detail.value;
				// this.areaIndex = e.detail.value;
				this.form.provinceNo = this.pickerRange[0][index[0]].code;
				this.form.cityNo = this.pickerRange[1][index[1]].code;
				this.form.areaNo = this.pickerRange[2][index[2]].code;

				this.form.provinceName = this.pickerRange[0][index[0]].name;
				this.form.cityName = this.pickerRange[1][index[1]].name;
				// this.form.areaName = this.pickerRange[2][index[2]].name;
				this.form.areaText = this.form.provinceName + '-' + this.form.cityName
				this.getSubBankList();
				this.$forceUpdate();
				// // 更新城市数据
				// if (this.pickerRange[1].length === 0 || this.pickerRange[1][0] !== this.selectedProvince) {
				// 	this.pickerRange[1] = addressData.city[this.selectedProvince];
				// }
				// // 更新区域数据
				// if (this.pickerRange[2].length === 0 || this.pickerRange[2][0] !== this.selectedCity) {
				// 	this.pickerRange[2] = addressData.area[this.selectedCity];
				// }
			},
			async getProvinceApiData(channelCode) {
				let res = await getProvinceApi({channelCode});
				this.provinceList = res.data;
				return res.data
			},
			async getCityApiData(code, channelCode) {
				let res = await getCityApi({
					code,channelCode
				});
				this.provinceList = res.data;
				return res.data
			},
			async getAreaApiData(code, channelCode) {
				let res = await getAreaApi({
					code,channelCode
				});
				this.provinceList = res.data;
				return res.data;
			},
			// 获取省
			getProvince(list) {
				let dataInfo = {};
				list.forEach((item, index) => {
					let {
						provinceCode,
						provinceName
					} = item;
					if (!dataInfo[provinceCode]) {
						dataInfo[provinceCode] = {
							value: provinceCode,
							text: provinceName,
							children: [],
						};
					}
					dataInfo[provinceCode].children.push(item);
				});
				let newList = Object.values(dataInfo); // list 转换成功的数据
				console.log({
					newList
				});
				return this.getCity(newList);
			},
			// 获取市
			getCity(list) {
				let dataInfoList = {};
				let listAll = []
				list.forEach((itemList, index) => {
					let dataInfo = {};
					let intList = itemList.children.forEach((item, index) => {
						let {
							cityCode,
							cityName
						} = item;
						if (!dataInfo[cityCode]) {
							dataInfo[cityCode] = {
								value: cityCode,
								text: cityName,
								children: [],
							};
						}
						item.value = item.districtCode
						item.text = item.districtName
						dataInfo[cityCode].children.push(item);
					});
					let getCityList = Object.values(dataInfo); // list 转换成功的数据
					itemList.children = [...getCityList]
					listAll.push(itemList)
				});
				console.log({
					listAll
				});
				return listAll
			},
			getAreaData() {
				// 获取接口的地址数据信息
				getProvinceCityList().then((res) => {
					// 获取地址转换
					const treeData = this.getProvince(res.data);
					this.areaData = treeData;
				});
			},
			async getData() {
				//let res = await queryCustomer({scanSerialno});
				let res = this.res;
				console.log('--------------------------------------');
				console.log(res);
				console.log('--------------------------------------');
				if (res) {
					this.bankImage = res.settleCardImgPath;
					this.bankBackImage = res.bankCardBackPic;
					this.form.settleCardNo = res.settleCardNo;
					this.form.bankName = res.bankName;
					this.form.phone = res.reservedPhone;
					this.form.bankCode = res.bankCode;
					this.form.provinceName = res.bankProvName;
					this.form.cityName = res.bankCityName;
					this.form.provinceNo = res.bankProv;
					this.form.cityNo = res.bankCity;
					this.form.bankType = res.bankType;
					// this.form.areaName = '东城区';
					// this.form.areaNo = '1021';
					if (res.bankProvName) {
						this.form.areaText =
							`${res.bankProvName}-${res.bankCityName}`;
					}

					this.form.stlBankNo = res.stlBankNo;
					this.form.stlBankNm = res.stlBankNm;
					console.log(this.form);
					if (this.form.provinceNo && this.form.bankName) {

						this.getSubBankList()
					}
				}
			},
			bankNameClick() {
				// this.$tip.toast("上传结算卡识别!");
			},
			chooseImg(type) {
				let _this = this;
				let chooseImgtype = ['album'];
				this.$selectUpload.chooseImg_(chooseImgtype).then(async (res) => {
					this.$tip.loading("上传中...");
					setTimeout(function() {
						_this.$tip.loaded();
					}, 10000);
					const size = res.tempFiles[0].size;
					// h5要单独压缩
					// // #ifdef H5
					// if (size > (1024 * 1024*4)) {
					// 	base64 = await this.$refs.wCompress2.start(res.tempFilePaths[0], {
					// 		pixels: 90000, // 最大分辨率，默认二百万
					// 		quality: 0.8, // 压缩质量，默认0.8
					// 		type: 'png', // 图片类型，默认jpg
					// 		base64: true // 是否返回base64，默认false，非H5有效
					// 	});
					// } else {
					// 	base64 = await this.getBase64(res.tempFilePaths[0]);
					// }
					// // #endif
					// // #ifndef H5
					// base64 = await this.getBase64(res.tempFilePaths[0]);
					// // #endif
					// let base64;
					if (size > (1024 * 1024 * 10)) {
						return this.$tip.toast('上传图片不超过10M!');
					}
					// base64 = await this.getBase64(res.tempFilePaths[0]);
					// let ocrInfo = await this.ocrGetInfo(base64, type);
					const file = res.tempFilePaths[0];
					let otherParams = {serialno : this.$storage.getStore('serialno')};
					
					let ocrInfo = await this.uploadApiRequest_(file, type,otherParams);
					this.$tip.loaded();
					// && ocrInfo.data.retultCode == "0000"
					if (ocrInfo.code == 200) {
						this.$tip.success("识别成功!");
						switch (type) {
							case '04':
								this.bankImage = ocrInfo.data.imgUrl;
								this.form.settleCardNo = ocrInfo.data.bankCardNo;
								this.form.bankName = ocrInfo.data.bankName;
								// this.bandCodeQuest();
								// 城市存在直接请求支行
								this.form.stlBankNo = '';
								this.form.stlBankNm = '';
								//if (this.form.bankName.indexOf('工商银行') !== -1) {
								//	return this.$tip.toast("不支持工商银行，请选择其他开户行!");
								//}
								if (this.form.provinceNo && this.form.bankName) {

									this.getSubBankList()
								}
								break;
							case '14':
								this.bankBackImage = ocrInfo.data.imgUrl;
								break;
							default:
								break;
						}
						console.log("this.bankBackImage", this.bankBackImage)
					} else {
						_this.$tip.loaded();
						_this.$tip.toast(ocrInfo.msg);
					}
				}).catch(e => {
					_this.$tip.toast(ocrInfo.msg);
					_this.$tip.loaded();
				});
			},
			async bankChange() {
				// await this.bandCodeQuest();
				await this.getSubBankList();
			},
			// 获取银行code
			async bandCodeQuest() {
				let data = await getBankCode({
					bankName: this.form.bankName,
					serialno: this.$storage.getStore('serialno'),
					pageNum: 1,
					pageSize: 10,
				});
				console.log({
					data,
				});
				if (data.data && data.data.list.length) {
					this.form.bankCode = data.data.list[0].code;
				} else {
					this.$tip.toast("没有查到对应银行,请重新输入!");
				}
			},
			// 获取支行列表
			async getSubBankList() {
				if (!this.form.cityNo || !this.form.cityName) {
					return this.$tip.toast("请选择开户行地址!");
				}
				console.log("this.form.bankName", this.form.bankName)
				if (this.form.bankName) {
					let data = await subBankCode({
						serialno : this.$storage.getStore('serialno'),
						provCode: this.form.provinceNo,
						cityCode: this.form.cityNo,
						bankCode: this.form.bankCode,
						bankName: this.form.bankName,
						settleCardNo: this.form.settleCardNo,
						// areaNo: this.form.areaNo,
						pageNum: 1,
						pageSize: 100,
					});
					if (data.data.list.length) {
						this.bankList = data.data.list;
					} else {
						return this.$tip.toast("未查到支行,请重试!");
					}
					// console.log("this.bankList", this.bankList);
				}
			},
			// onchange(e) {
			// 	let areaObj = e.detail.value[2];
			// 	this.form.area = areaObj;
			// 	this.form.provinceNo = areaObj.provinceCode;
			// 	this.form.provinceName = areaObj.provinceName;
			// 	this.form.cityName = areaObj.cityName;
			// 	this.form.cityNo = areaObj.cityCode;
			// 	this.form.areaNo = areaObj.districtCode;
			// 	this.form.areaName = areaObj.districtName;
			// 	this.form.allArea =
			// 		areaObj.provinceName + areaObj.cityName + areaObj.districtName;
			// 	this.$forceUpdate();
			// 	this.getSubBankList();
			// },
			// 地址确定
			areaConfirm(areaValue) {
				const {
					province,
					city,
					area
				} = areaValue;
				this.form.area = areaValue;
				this.form.provinceName = province.label;
				this.form.cityName = city.label;
				this.form.areaName = area.label;
				this.form.provinceNo = province.value.padEnd(6, '0');
				this.form.cityNo = city.value.padEnd(6, '0');
				// this.form.areaNo = area.value.padEnd(6, '0');
				this.form.allArea = `${province.label}-${city.label}`;
				this.$forceUpdate();
				this.getSubBankList();
				console.log("this.form", this.form)
			},
			// strNum(value){
			// 	.padEnd(5, '0')
			// },
			sendCode() {
				// if (this.second >= 0) {
				//   clearInterval(this.t imeNo)
				//   return;
				// }
				this.second = 90;
				this.timeNo = setInterval(() => {
					this.second--;
					if (this.second <= 0) {
						clearInterval(this.timeNo);
						this.disabled = false;
					}
				}, 1000);
			},
			async sms() {
				const phoneReg = /^1[3-9]\d{9}$/;
				if (this.disabled) {
					return;
				}
				if (!this.form.phone || !phoneReg.test(this.form.phone)) {
					return this.$tip.toast("请正确输入手机号!");
				}
				this.disabled = true;
				let params = await this.signParams(this.form.phone);
				params.serialno=this.$storage.getStore('serialno');
				smsSend(params)
					.then((res) => {
						if (res.code === 200) {
							this.sendCode();
						} else {
							this.disabled = false;
						}
					})
					.catch((err) => {
						this.disabled = false;
					});
			},
			async cardSubmit() {
				if (!this.form.settleCardNo) {
					return this.$tip.toast("请输入结算卡号!");
				}
				if (!this.form.phone) {
					return this.$tip.toast('请输入预留手机号!');
				}
				if (!this.form.provinceNo || !this.form.provinceName) {
					return this.$tip.toast("请选择开户行地址!");
				}
				//if (this.form.bankName.indexOf('工商银行') !== -1) {
				//	return this.$tip.toast("不支持工商银行，请选择其他开户行!");
				//}
				if (!this.form.bankName) {
					return this.$tip.toast("请输入开户行名称!");
				}
				// 机具扫码进入,而且是商户入驻
				//if (this.terminalInto && this.type == 4) {
					if (!this.form.scanSmsCode) {
						return this.$tip.toast('请输入验证码!');
					}
				//}

				if (!this.form.stlBankNo || !this.form.stlBankNm) {
					return this.$tip.toast("请选择支行!");
				}
				let params = {
					settleCardNo: this.form.settleCardNo,
					phone: this.form.phone,
					scanSmsCode: this.form.scanSmsCode,
					bankName: this.form.bankName,
					bankCode: this.form.bankCode,
					stlBankNo: this.form.stlBankNo,
					stlBankNm: this.form.stlBankNm,
					bankProv: this.form.provinceNo,
					bankProvName: this.form.provinceName,
					bankCityName: this.form.cityName,
					bankCity: this.form.cityNo,
					editSettleCardImgPath: this.bankImage,
					bankType: this.form.bankType,
				};
				// 机具扫码进入
				//if (this.terminalInto) {
					params.scanSmsCode = this.form.scanSmsCode
				//}
				this.$storage.setStore("certificationOcr2", params);
				this.$storage.setStore("cardFormData", this.form);
				// console.log(params)
				// return
				// this.$tip.loading('提交中....');
				if (this.type == 4) {
					this.$emit("cardSubmit", params, 2);
				} else {
					this.$emit("cardSubmit", params);
				}
			},
			pickerConfirmHandle(e) {
				console.log(e);
				if (this.bankList.length) {
					this.bankChooseIndex = e.detail.value;
					this.form.stlBankNo = this.bankList[this.bankChooseIndex].code;
					this.form.stlBankNm = this.bankList[this.bankChooseIndex].name;
					this.form.bankType = this.bankList[this.bankChooseIndex].bankType;
					this.form.bankCode = this.bankList[this.bankChooseIndex].bankCode;
					// const bankType = this.bankList[this.bankChooseIndex].bankType;
					// console.log({bankType});
					// if(bankType){
					// 	this.form.bankType = bankType;
					// }
					this.$forceUpdate();
				}
			},
			backSubmit() {
				this.$emit("backSubmit", 1);
			},

		},
	};
</script>

<style lang="scss">
	page {
		// padding: 20upx 0;
	}

	.image-box {
		display: flex;
		justify-content: space-between;
		background-color: #ffffff;
	}

	.img-upload {
		background-color: #ffffff;
		padding: R(30px);

		.top-tips {
			text-align: left;
			font-size: R(24px);
			color: #C7C7C7;
			padding-top: R(40px);
			margin-bottom: R(20px);

			.red {
				margin-left: R(10px);
				color: red;
			}
		}

		.box-image {
			background-color: #dfdfe8;
			border-radius: R(10px);
			padding: R(20px);
			width: R(280px);
			// height: R(250px);
			margin: 0 auto;
			position: relative;

			.bg-image {
				width: R(240px);
				height: R(120px);
				margin: 0 auto;
			}

			.add {
				width: R(88px);
				height: R(88px);
				background-color: #3bc3ff;
				border-radius: 50%;
				text-align: center;
				font-size: R(80);
				line-height: R(78px);
				color: #ffffff;
				position: absolute;
				top: 50%;
				left: 50%; //居中
				margin-left: R(-44px);
				margin-top: R(-44);
			}
		}

		.tips {
			text-align: center;
			margin: R(30px);
			font-size: R(25px);
			color: #1e1e20;
			font-weight: 400;
		}
	}

	.form {
		margin: R(30px) 0;

		.item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 25upx 20upx;
			font-size: 28upx;
			font-weight: 400;
			color: #262626;
			background: #fff;

			.input {
				flex: 1;
				text-align: right;
				margin-left: auto;
				font-size: 28upx;
				color: #7d7d7d;
			}

			.sendCode {
				margin-left: 10upx;
			}
		}

		.next {
			margin: 40upx auto 0;
			width: 581upx;
			height: 80upx;
			line-height: 80upx;
			text-align: center;
			background: $themeColor;
			border-radius: 10upx;
			font-size: 30upx;
			font-weight: 400;
			color: #ffffff;
		}

		.sub-tips {
			padding: 28upx 30upx;
			font-size: 26upx;
			font-weight: 400;
			color: #999999;
		}
	}

	.card-btn {
		.button {
			width: 45%;
			margin: R(30px);
			flex: 1;
		}
	}
</style>